// -----------------------------------------------------------------------
//  <copyright file="DictionaryType.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-17 01:10</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Domain.Entity;
using DaprPlus.DataDicts.Domain.Dtos;
using DaprPlus.Domain;


namespace DaprPlus.DataDicts.Domain.Entities;

[Description("数据字典类型")]
public class DictionaryType : EntityBase, ILockable, ICreationTime, IAggregateRoot
{
    public required string Name { get; set; }
    public required string Code { get; set; }
    public string? Remark { get; set; }
    public DateTime CreatedTime { get; set; }
    public bool IsLocked { get; set; }
    public virtual List<DictionaryItem> Items { get; set; } = new();

    public ApiResult AddItem(params DictionaryItemInDto[] dtos)
    {
        foreach (var dto in dtos)
        {
            if (Items.Any(m => m.Value == dto.Value))
            {
                return ApiResult.Error($"字典类型 {Code} 下已存在值为 {dto.Value} 的字典项");
            }

            var item = new DictionaryItem
            {
                Label = dto.Label,
                Value = dto.Value,
                Remark = dto.Remark,
                Order = dto.Order,
                Icon = dto.Icon,
                Color = dto.Color,
                IsLocked = dto.IsLocked,
                CreatedTime = DateTime.Now,
                DictionaryTypeId = Id
            };
            if (item.Order == 0 && Items.Count > 0)
            {
                item.Order = Items.Max(m => m.Order) + 1;
            }
            item.SetId();
            Items.Add(item);
        }
        return ApiResult.Success();
    }

    public ApiResult UpdateItem(params DictionaryItemInDto[] dtos)
    {
        foreach (var dto in dtos)
        {
            var existingItem = Items.FirstOrDefault(m => m.Id == dto.Id);
            if (existingItem == null)
            {
                return ApiResult.Error($"字典类型 {Code} 下不存在编号为 {dto.Id} 的字典项");
            }

            // 检查值是否重复（排除当前项和已删除的项）
            if (Items.Any(m => m.Id != dto.Id && m.Value == dto.Value))
            {
                return ApiResult.Error($"字典类型 {Code} 下已存在值为 {dto.Value} 的字典项");
            }

            existingItem.Label = dto.Label;
            existingItem.Value = dto.Value;
            existingItem.Remark = dto.Remark;
            existingItem.Order = dto.Order;
            existingItem.Icon = dto.Icon;
            existingItem.Color = dto.Color;
            existingItem.IsLocked = dto.IsLocked;
        }
        return ApiResult.Success();
    }

    public ApiResult RemoveItem(string value)
    {
        var existingItem = Items.FirstOrDefault(m => m.Value == value);
        if (existingItem == null)
        {
            return ApiResult.Error($"字典类型 {Code} 下不存在值为 {value} 的字典项");
        }

        Items.Remove(existingItem);
        return ApiResult.Success();
    }

    public ApiResult RemoveItem(params long[] ids)
    {
        var itemsToRemove = Items.Where(m => ids.Contains(m.Id)).ToList();
        var notFoundIds = ids.Where(id => Items.All(item => item.Id != id)).ToList();

        if (notFoundIds.Any())
        {
            return ApiResult.Error($"字典类型 {Code} 下不存在编号为 {string.Join(", ", notFoundIds)} 的字典项");
        }

        // 检查是否有未锁定的字典项
        var unlockedItems = itemsToRemove.Where(item => !item.IsLocked).ToList();
        if (unlockedItems.Any())
        {
            var unlockedLabels = string.Join(", ", unlockedItems.Select(item => item.Label));
            return ApiResult.Error($"以下字典项未锁定，无法删除：{unlockedLabels}");
        }

        foreach (var item in itemsToRemove)
        {
            Items.Remove(item);
        }
        return ApiResult.Success();
    }
}
